package chan.project.smartlawdatamanage.consumer;

import chan.project.smartlawcommon.config.KafkaTopicConfig;
import chan.project.smartlawdatamanage.service.LawRegulationInvokeLogService;
import chan.project.smartlawdatamanage.service.TemLawRegulationInvokeLogService;
import chan.project.smartlawmodel.dto.lawregulation.LawRegulationMessage;
import chan.project.smartlawmodel.entity.LawRegulationInvokeLog;
import chan.project.smartlawmodel.entity.TemLawRegulationInvokeLog;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class LegalMessageConsumer {

    @Resource
    private LawRegulationInvokeLogService lawRegulationInvokeLogService;

    @Resource
    private TemLawRegulationInvokeLogService temLawRegulationInvokeLogService;

    @KafkaListener(topics = KafkaTopicConfig.LEGAL_TOPIC, groupId = "legal-group")
    public void consumeLegalMessage(String message) {
        try {
            List<LawRegulationMessage> lawMessages = JSONUtil.toList(message, LawRegulationMessage.class);
            log.info("正在存储{}条法律调用信息", lawMessages.size());
            //存储调用日志
            List<LawRegulationInvokeLog> validLogs = new ArrayList<>();
            List<LawRegulationMessage> failedMessages = new ArrayList<>(); // 假设原始类型是 InstrumentMessage

            for (LawRegulationMessage msg : lawMessages) {
                LawRegulationInvokeLog log = msg.toLawRegulationInvokeLog(msg);
                if (log.getRegulationId() != null) {
                    validLogs.add(log);
                } else {
                    failedMessages.add(msg);
                }
            }
            lawRegulationInvokeLogService.saveBatch(validLogs);
            //存储暂时不存在的法律法规
            saveNotDefinedLaw(failedMessages);
        } catch (Exception e) {
            log.error("存储法律调用信息失败", e);
        }
    }

    /**
     * 存储暂不存在的法律
     */
    public void saveNotDefinedLaw(List<LawRegulationMessage> lawMessages) {
        List<TemLawRegulationInvokeLog> collect = lawMessages.stream()
                .map(instrumentMessage -> instrumentMessage.toTemLawRegulationInvokeLog(instrumentMessage))
                .collect(Collectors.toList());
        boolean b = temLawRegulationInvokeLogService.saveBatch(collect);
        if (!b) {
            log.error("存储临时法律调用信息失败");
        }
    }
}